package com.docios.cookbook2.utils;

import android.util.Log;

import androidx.annotation.NonNull;

import com.docios.cookbook2.entity.QueryBean;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class NetUtil {
    static String formattedUrl = "";
    /*
    * 一层嵌套为数组的json
    * */
    public interface OnArrayQueriedCallBack {
        void onSuccess(List<QueryBean> queryBeans);

        void onFailure(Exception e);
    }

    /*
    * 一层嵌套为对象的json
    * */
      public interface OnObjectQueriedCallBack {
        void onSuccess(QueryBean queryBean);

        void onFailure(Exception e);
    }

    /*
     * 极速数据api
     * byKeyword: https://api.jisuapi.com/recipe/search?keyword=%E7%99%BD%E8%8F%9C&num=10&appkey=%s
     * forClassResult: https://api.jisuapi.com/recipe/class?appkey=yourappkey
     * byClass: https://api.jisuapi.com/recipe/byclass?classid=2&start=0&num=10&appkey=yourappkey
     * byId: https://api.jisuapi.com/recipe/detail?id=5&appkey=yourappkey
     *  */
    public static void queryRecipeFromJisuapi(@NonNull Map<String, String> map, final OnArrayQueriedCallBack callBack) {

        OkHttpClient okHttpClient = new OkHttpClient();

        //根据分类查询参数 OK!
        if (map.containsKey("classid")) {
            formattedUrl = String.format(Objects.requireNonNull(map.get("host")),
                    map.get("classid"),
                    map.get("start"),
                    map.get("appkey"));
        }
        //根据id
        if (map.containsKey("id")) {
            formattedUrl = String.format(Objects.requireNonNull(map.get("host")),
                    map.get("id"),
                    map.get("appkey"));
        }
        //根据菜名
        if (map.containsKey("keyword")) {
            formattedUrl = String.format(Objects.requireNonNull(map.get("host")),
                    map.get("keyword"),
                    map.get("appkey"));
        }

        /*
         * 请求开始
         * */
        Request request = new Request.Builder()
                .url(formattedUrl)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                callBack.onFailure(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("#######httpResponse", "onResponse: " + response);
                try {
                    assert response.body() != null;
                    String jsonString = response.body().string();

                    List<QueryBean> queryBeans = new JsonUtil().jsonForArray(jsonString);

                    callBack.onSuccess(queryBeans);
                    Log.i("########rawBeans", "onResponse: " + queryBeans.toString());
                } catch (Exception e) {
                    callBack.onFailure(e);
                }
            }
        });
    }

    /*
     * 阿里云api
     * byKeyword: http://jsucpdq.market.alicloudapi.com/recipe/search?keyword=白菜&num=10&start=1
     * forClassResult: https://jsucpdq.market.alicloudapi.com/recipe/class
     * byClass: https://jsucpdq.market.alicloudapi.com/recipe/byclass?classid=2&num=10&start=0
     * byId: https://jsucpdq.market.alicloudapi.com/recipe/detail?id=5
     * */
    public static void queryArrayFromAli(@NonNull Map<String, String> map, final OnArrayQueriedCallBack callBack) {

        OkHttpClient okHttpClient = new OkHttpClient();

        //根据分类 OK!
        if (map.containsKey("classid")) {
            formattedUrl = String.format(Objects.requireNonNull(map.get("host")),
                    map.get("classid"),
                    map.get("start"),
                    map.get("appcode"));
        }
        //TODO 根据id NO
//        if (map.containsKey("id")) {
//            formattedUrl = String.format(Objects.requireNonNull(map.get("host")),
//                    map.get("id"),
//                    map.get("appcode"));
//        }
        //根据菜名 OK!
        if (map.containsKey("keyword")) {
            formattedUrl = String.format(Objects.requireNonNull(map.get("host")),
                    map.get("keyword"),
                    map.get("start"),
                    map.get("appcode"));
        }

        /*
         * 请求开始
         * */
        Request request = new Request.Builder()
                .url(formattedUrl)
                .header("Authorization", Objects.requireNonNull(map.get("appcode")))
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                callBack.onFailure(e);
            }
            //响应，得到raw数据
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("#######httpResponse", "onResponse: " + response);
                try {
                    assert response.body() != null;
                    String jsonString = response.body().string();
                    //json解析
                    List<QueryBean> queryBeans = new JsonUtil().jsonForArray(jsonString);
                    //ok,返回数据
                    callBack.onSuccess(queryBeans);
                    Log.i("########rawBeans", "onResponse: " + queryBeans.toString());
                } catch (Exception e) {
                    callBack.onFailure(e);
                }
            }
        });
    }

   public static void queryObjectFromAli(@NonNull Map<String, String> map, final OnObjectQueriedCallBack callBack) {

        OkHttpClient okHttpClient = new OkHttpClient();

        // 根据id
        if (map.containsKey("id")) {
            formattedUrl = String.format(Objects.requireNonNull(map.get("host")),
                    map.get("id"),
                    map.get("appcode"));
        }

        /*
         * 请求开始
         * */
        Request request = new Request.Builder()
                .url(formattedUrl)
                .header("Authorization", Objects.requireNonNull(map.get("appcode")))
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                callBack.onFailure(e);
            }
            //响应，得到raw数据
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("#######httpResponse", "onResponse: " + response);
                try {
                    assert response.body() != null;
                    String jsonString = response.body().string();
                    //json解析
                    QueryBean queryBean = new JsonUtil().jsonForObject(jsonString);
                    //ok,返回数据
                    callBack.onSuccess(queryBean);
                    Log.i("########rawBeans", "onResponse: " + queryBean);
                } catch (Exception e) {
                    callBack.onFailure(e);
                }
            }
        });
    }


}
